import { defineConfig, loadEnv } from "vite";
import vue from "@vitejs/plugin-vue";
import path from "path";
import { VitePWA } from "vite-plugin-pwa";
import postcssPxtorem from "postcss-pxtorem";
import legacy from "@vitejs/plugin-legacy";
export default defineConfig(({ mode }) => {
  // 加载环境变量
  const env = loadEnv(mode, process.cwd(), "");

  return {
    plugins: [
      vue(),
      legacy({
        targets: ["chrome >= 60"],
        additionalLegacyPolyfills: [
          "regenerator-runtime/runtime",
          "core-js/stable/global-this",
          "core-js/stable/promise",
          "core-js/stable/array/iterator",
        ],
        modernPolyfills: ["es.global-this"],
        renderLegacyChunks: true, // 强制转译所有依赖
      }),
      VitePWA({
        includeAssets: ["favicon.ico", "apple-touch-icon.png"],
        manifest: {
          name: env.VITE_APP_TITLE || "My App",
          short_name: "App",
          theme_color: "#ffffff",
          icons: [
            {
              src: "/android-chrome-192x192.png",
              sizes: "192x192",
              type: "image/png",
            },
            {
              src: "/android-chrome-512x512.png",
              sizes: "512x512",
              type: "image/png",
            },
          ],
        },
      }),
    ],
    define: {
      __APP_TITLE__: JSON.stringify(env.VITE_APP_TITLE || "默认标题"),
      "import.meta.env.VITE_APP_TITLE": JSON.stringify(env.VITE_APP_TITLE),
    },
    server: {
      host: "0.0.0.0",
      port: 3000,
      strictPort: true,
      headers: {
        "X-UA-Compatible": "IE=Edge,chrome=1", // 强制兼容模式
      },
      proxy:
        env.VITE_APP_ENV === "development"
          ? {
              "/api": {
                target: env.VITE_API_BASE_URL,
                changeOrigin: true,
                rewrite: (path) => path.replace(/^\/api/, ""),
              },
            }
          : undefined,
      hmr: {
        protocol: "ws",
        host: "localhost",
      },
    },
    resolve: {
      alias: {
        "@": path.resolve(__dirname, "./src"),
        "crypto-js": path.resolve(__dirname, "node_modules/crypto-js"),
      },
    },
    css: {
      devSourcemap: true, // 开发模式生成 Sourcemap
      postcss: {
        plugins: [
          postcssPxtorem({
            rootValue: 16, // 1rem = 16px
            propList: ["*"], // 转换所有 CSS 属性
            selectorBlackList: [/^html$/], // 不转换 html 的 font-size
          }),
        ],
      },
    },
    build: {
      outDir: "dist",
      emptyOutDir: true,
      chunkSizeWarningLimit: 1500,
      minify: mode === "production" ? "terser" : false,
      sourcemap: mode !== "production",
      assetsDir: "assets",
      target: "es2015", // 新增：强制降级至 ES2015
      modulePreload: {
        polyfill: false, // 替代原来的 polyfillModulePreload
      },
      cssTarget: "chrome60", // 强制 CSS 兼容
      terserOptions: {
        compress: {
          drop_console: true,
          drop_debugger: true,
        },
      },
      rollupOptions: {
        output: {
          entryFileNames: "assets/[name]-[hash].js",
          chunkFileNames: "assets/[name]-[hash].js",
          assetFileNames: "assets/[name]-[hash].[ext]",
          format: "iife", // 强制IIFE包裹（兼容性最佳）
          manualChunks: {
            vant: ["vant"],
            vue: ["vue", "vue-router"],
          },
        },
      },
    },
    assetsInclude: ["**/*.png"],
    base: "./",
  };
});
// import { defineConfig, loadEnv } from "vite";
// import vue from "@vitejs/plugin-vue";
// import path from "path";
// import { VitePWA } from "vite-plugin-pwa";
// import basicSsl from '@vitejs/plugin-basic-ssl'; // 导入 basic-ssl 插件

// export default defineConfig(({ mode }) => {
//   // 加载环境变量
//   const env = loadEnv(mode, process.cwd(), "");
//   return {
//     plugins: [
//       vue(),
//       basicSsl(), // 启用基本 SSL 支持
//       VitePWA({
//         includeAssets: ["favicon.ico", "apple-touch-icon.png"],
//         manifest: {
//           name: env.VITE_APP_TITLE || "My App",
//           short_name: "App",
//           theme_color: "#ffffff",
//           icons: [
//             {
//               src: "/android-chrome-192x192.png",
//               sizes: "192x192",
//               type: "image/png",
//             },
//             {
//               src: "/android-chrome-512x512.png",
//               sizes: "512x512",
//               type: "image/png",
//             },
//           ],
//         },
//       }),
//     ],
//     define: {
//       __APP_TITLE__: JSON.stringify(env.VITE_APP_TITLE || "默认标题"),
//       "import.meta.env.VITE_APP_TITLE": JSON.stringify(env.VITE_APP_TITLE),
//     },
//     server: {
//       host: "0.0.0.0",
//       port: 3000,
//       strictPort: true,
//       https: true, // 启用 HTTPS
//       proxy: env.VITE_APP_ENV === "development"
//         ? {
//             "/api": {
//               target: env.VITE_API_BASE_URL,
//               changeOrigin: true,
//               secure: false, // 如果代理目标是 HTTPS 可能需要这个选项
//               rewrite: (path) => path.replace(/^\/api/, ""),
//             },
//           }
//         : undefined,
//       hmr: {
//         protocol: "wss", // 使用 WebSocket Secure
//         host: "localhost",
//       },
//     },
//     resolve: {
//       alias: {
//         "@": path.resolve(__dirname, "./src"),
//         "crypto-js": path.resolve(__dirname, "node_modules/crypto-js"),
//       },
//     },
//     base: "./",
//     build: {
//       assetsDir: "assets",
//       minify: "terser",
//       terserOptions: {
//         compress: {
//           drop_console: true,
//           drop_debugger: true,
//         },
//       },
//       rollupOptions: {
//         output: {
//           entryFileNames: "assets/[name]-[hash].js",
//           chunkFileNames: "assets/[name]-[hash].js",
//           assetFileNames: "assets/[name]-[hash].[ext]",
//           manualChunks: {
//             vant: ["vant"],
//             vue: ["vue", "vue-router"],
//           },
//         },
//       },
//     },
//     assetsInclude: ["**/*.png"],
//   };
// });
